import { createHtmlPlugin } from 'vite-plugin-html';
import { getCdnLinks, getCdnScripts } from './cdn-config';

export const configHtmlPlugin = (env: Record<string, string>) => {
  const {
    VITE_APP_NODE_ENV: appEnv,
    VITE_APP_NAME: appName,
    VITE_APP_NAME_ZH: appNameZh,
    VITE_APP_ROOT: appRoot,
    VITE_APP_PUBLIC_DIR: appPublicDir,
    VITE_APP_LOGO_DIR: appFaviconDir,
    NODE_ENV: nodeEnv,
  } = env;

  const isProduction = nodeEnv === 'production';

  return createHtmlPlugin({
    minify: isProduction,
    inject: {
      data: {
        // 出现在模版中的 <%- title %>
        title: appNameZh,
        faviconDir: appFaviconDir,
        injectStyle: `
          <style>
            /* 预加载关键CSS */
            #app { display: none; }
            .loading {
              display: flex;
              justify-content: center;
              align-items: center;
              height: 100vh;
              font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            }
            .loading::after { content: '加载中...'; }
          </style>
        `,
        injectHeadCDN: getCdnLinks(isProduction).join('\n        '),
        injectBodyCDN: getCdnScripts(isProduction).join('\n        '),
        injectScript: `
          <script>
            window.$_vite_app_env = '${appEnv}';
            window.$_vite_app_name = '${appName}';
            window.$_vite_app_name_zh = '${appNameZh}';
            window.$_vite_app_root = '${appRoot}';
            window.$_vite_app_public_dir = '${appPublicDir}';

            // 性能监控
            window.performance && window.performance.mark && window.performance.mark('app-start');

            // 资源预加载配置
            ${isProduction ? `
            // 预加载关键资源
            function preloadResource(url, as = 'script') {
              const link = document.createElement('link');
              link.rel = 'preload';
              link.href = url;
              link.as = as;
              if (as === 'style') link.crossOrigin = 'anonymous';
              document.head.appendChild(link);
            }
            ` : ''}
          </script>
        `,
      },
    },
  });
};
